package com.xgp.forkjoin;

import org.junit.Test;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 求和计算
 */
public class Demo1 extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private Long temp = 10000L;

    public Demo1(Long start, Long end) {
        this.start = start;
        this.end = end;
    }
    /**
     * 计算方法
     * @return
     */
    @Override
    protected Long compute() {
        if(end - start < temp) {
            Long sum = 0L;
            for (Long i = start;i <= end;i++) {
                sum += i;
            }
            return sum;
        }else {            //分支合并计算
            long middle = (start + end) / 2;//中间值
            Demo1 task1 = new Demo1(start, middle);
            task1.fork();   //把任务压入线程对队列
            Demo1 task2 = new Demo1(middle, end);
            task2.fork();

            return task1.join() + task2.join();
        }
    }
}
